"use client"

import { useState, useEffect } from 'react';
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription, DialogFooter } from '@/components/ui/dialog';
import { Label } from '@/components/ui/label';
import { Input } from '@/components/ui/input';
import { Button } from '@/components/ui/button';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { addPlayer } from '@/lib/data';
import { Region } from '@/types/player';
import { Save, X } from 'lucide-react';

interface AddPlayerFormProps {
  onClose: () => void;
  onSuccess: () => void;
}

export default function AddPlayerForm({ onClose, onSuccess }: AddPlayerFormProps) {
  const [formData, setFormData] = useState({
    name: '',
    avatar: '',
    region: '',
    region_id: '',
    region_color: '',
    is_blacklisted: false,
  });
  const [isLoading, setIsLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [regions, setRegions] = useState<Region[]>([]);

  useEffect(() => {
    // 加载地区数据
    const loadRegions = async () => {
      try {
        const response = await fetch('/api/regions');
        if (!response.ok) {
          throw new Error('获取地区数据失败');
        }
        const data = await response.json();
        setRegions(data || []);
      } catch (error) {
        console.error('加载地区数据失败', error);
        // 使用默认数据作为备份
        setRegions([
          { id: '1', name: '亚洲', color: '#FF5555' },
          { id: '2', name: '欧洲', color: '#55AAFF' },
          { id: '3', name: '北美', color: '#55FF55' },
          { id: '4', name: '南美', color: '#FFAA55' },
          { id: '5', name: '大洋洲', color: '#AA55FF' },
        ]);
      }
    };
    
    loadRegions();
  }, []);

  const handleChange = (field: string, value: any) => {
    setFormData(prev => ({
      ...prev,
      [field]: value
    }));
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    
    if (!formData.name || formData.name.trim() === '') {
      setError('玩家名称不能为空');
      return;
    }
    
    setIsLoading(true);
    setError(null);
    
    try {
      await addPlayer(formData);
      onSuccess();
    } catch (err: any) {
      console.error('添加玩家失败:', err);
      setError(err.message || '添加玩家失败，请稍后重试');
    } finally {
      setIsLoading(false);
    }
  };

  const handleRegionChange = (regionId: string) => {
    const selectedRegion = regions.find(r => r.id === regionId);
    if (selectedRegion) {
      setFormData(prev => ({
        ...prev,
        region_id: selectedRegion.id,
        region: selectedRegion.name,
        region_color: selectedRegion.color
      }));
    }
  };

  return (
    <Dialog open={true} onOpenChange={onClose}>
      <DialogContent className="bg-[#1a1d24] border border-gray-800 text-white sm:max-w-[425px]">
        <DialogHeader>
          <DialogTitle>添加新玩家</DialogTitle>
          <DialogDescription className="text-gray-400">
            填写玩家信息并点击添加按钮。
          </DialogDescription>
        </DialogHeader>
        
        <form onSubmit={handleSubmit} className="space-y-4">
          <div className="space-y-3">
            <div className="grid grid-cols-4 items-center gap-4">
              <Label htmlFor="name" className="text-right">
                名称*
              </Label>
              <Input
                id="name"
                value={formData.name}
                onChange={(e) => handleChange('name', e.target.value)}
                placeholder="玩家名称"
                className="col-span-3 bg-[#252a33] border-gray-700"
                required
              />
            </div>
            
            <div className="grid grid-cols-4 items-center gap-4">
              <Label htmlFor="avatar" className="text-right">
                头像
              </Label>
              <Input
                id="avatar"
                value={formData.avatar}
                onChange={(e) => handleChange('avatar', e.target.value)}
                placeholder="头像URL (可选)"
                className="col-span-3 bg-[#252a33] border-gray-700"
              />
            </div>
            
            <div className="grid grid-cols-4 items-center gap-4">
              <Label htmlFor="region" className="text-right">
                地区
              </Label>
              <Select
                value={formData.region_id}
                onValueChange={handleRegionChange}
              >
                <SelectTrigger className="col-span-3 bg-[#252a33] border-gray-700">
                  <SelectValue placeholder="选择地区 (可选)" />
                </SelectTrigger>
                <SelectContent className="bg-[#2a2e35] border-gray-700 text-white">
                  {regions.map(region => (
                    <SelectItem key={region.id} value={region.id} className="focus:bg-gray-700">
                      <div className="flex items-center">
                        <span
                          className="w-3 h-3 rounded-full mr-2"
                          style={{ backgroundColor: region.color }}
                        ></span>
                        {region.name}
                      </div>
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </div>
            
            <div className="grid grid-cols-4 items-center gap-4">
              <Label htmlFor="blacklist" className="text-right">
                黑名单
              </Label>
              <div className="col-span-3 flex items-center">
                <input
                  type="checkbox"
                  id="blacklist"
                  checked={formData.is_blacklisted}
                  onChange={(e) => handleChange('is_blacklisted', e.target.checked)}
                  className="rounded border-gray-700 bg-[#252a33] focus:ring-blue-500 h-4 w-4 mr-2"
                />
                <Label htmlFor="blacklist">将玩家加入黑名单</Label>
              </div>
            </div>
          </div>
          
          {error && (
            <div className="bg-red-500/20 border border-red-500 text-red-300 p-3 rounded">
              {error}
            </div>
          )}
          
          <DialogFooter className="mt-4">
            <Button 
              type="button" 
              variant="ghost" 
              onClick={onClose}
              disabled={isLoading}
              className="border border-gray-700 hover:bg-gray-800"
            >
              <X className="h-4 w-4 mr-2" />
              取消
            </Button>
            <Button 
              type="submit" 
              disabled={isLoading}
              className="bg-blue-600 hover:bg-blue-700"
            >
              {isLoading ? (
                <>
                  <span className="animate-spin h-4 w-4 mr-2 border-2 border-white border-t-transparent rounded-full"></span>
                  添加中...
                </>
              ) : (
                <>
                  <Save className="h-4 w-4 mr-2" />
                  添加玩家
                </>
              )}
            </Button>
          </DialogFooter>
        </form>
      </DialogContent>
    </Dialog>
  );
} 